#include "WaterParticleSystem.h"

#include <iostream>
using namespace std;

WaterParticleSystem::WaterParticleSystem(CubePileGrid * cubes, int numParticles)
{
	maxNumParticles = numParticles;
	emitter = new WaterDropEmitter(cubes, numParticles);
	particleList = new WaterParticle* [numParticles];
	for(int i=0; i< numParticles; i++)
	{
		particleList[i] = new WaterParticle();
	}
}

void WaterParticleSystem::animate(float timeD)
{
//	cout << "beginning particle system animate timeD=" << timeD << "\n";
	WaterParticle * lastDeadParticle = NULL;
	for(int i=0; i < maxNumParticles; i++)
	{
		if(particleList[i]->alive)
		{
//			cout << "found live particle: animating" << "\n";
			particleList[i]->animate(timeD);
		}
		else
		{
//			cout << "found dead particle, I'll save this one for later" << "\n";
			lastDeadParticle = particleList[i];
		}
	}
	
//	cout << "finished animating particles..."<< "\n";
	if(lastDeadParticle != NULL)
	{
//		cout << "there's space for a new particle, give the emitter a chance to reUse this old one"<< "\n";
		emitter->freeParticle = lastDeadParticle;
		emitter->emit(timeD);
	}
	
//	cout << "testing for collisions..."<< "\n";
	for(int i=0; i < maxNumParticles; i++)
	{
		if(particleList[i]->alive)
		{
			particleList[i]->testForAndHandleCollisions();
		}
	}
//	cout << "all done, function returning."<< "\n";
}

void WaterParticleSystem::render()
{
//	cout << "rendering particles...\n";
	for(int i=0; i < maxNumParticles; i++)
	{
		if(particleList[i]->alive)
		{
//			cout << "found live particle, rendering\n";
			particleList[i]->render();
		}
	}
//	cout << "all done, function returning.\n";
}
